import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '@/views/Index.vue'
import Login from '@/views/Login.vue'
import ChatPublic from '@/views/ChatPublic.vue'
import ChatPrivate from '@/views/ChatPrivate.vue'
import Register from '@/views/Register.vue'
// 在axios响应拦截器中处理newToken
import axios from 'axios'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/index',
    name: 'Index',
    component: Index
  },
  {
    path: '/chat',
    name: 'ChatPublic',
    component: ChatPublic,
    meta: { requiresAuth: true }
  },
  {
    path: '/chat/private/:username',
    component: ChatPrivate,
    meta: { requiresAuth: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    if (!user.token) {
      next({ path: '/login', query: { redirect: to.fullPath } })
    } else {
      next()
    }
  } else {
    next()
  }
})



axios.interceptors.response.use(response => {
  // 检查响应头中是否有newToken
  const newToken = response.headers['New-Token'] || response.headers['new-token']
  const tokenExpired = response.headers['Token-Expired'] || response.headers['token-expired']
  if (newToken) {
    // 更新本地存储中的token
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    user.token = newToken
    localStorage.setItem('user', JSON.stringify(user))
  }
  
  if (tokenExpired) {
    
    // 清除用户信息，防止重复登录
    localStorage.removeItem('user') 
    Vue.prototype.$bug && Vue.prototype.$bug.$emit('token-expired')
    // 跳转到登录页面
    router.push('/login')
    Vue.prototype.$message.error('登录已过期，请重新登录')
  }
  return response
}, error => {
  return Promise.reject(error)
})

export default router